package net.zoneland.knowledge.utils;

import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.enums.CmpDnEnum;

/**
 * 组织信息工具类.
 * @author zmq
 * @Date 2021/12/2 15:05
 */
public final class OrgInfoUtils {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(OrgInfoUtils.class);
    /**
     * 匹配分公司dn的正则.
     */
    private static final Pattern SUB_COMPANY_DN_PATTERN
        = Pattern.compile("(hz|nb|wz|jx|sx|jh|tz|qz|hu|ls|zs)zmcc\\S*$");

    /**
     * 私有构造.
     */
    private OrgInfoUtils() {

    }


    /**
     * 获取公司dn.
     * @param deptDn 部门dn
     * @return 公司dn
     */
    public static String getCompanyDn(final String deptDn) {
        if (StringUtils.isBlank(deptDn)) {
            return null;
        }
        if (CmpDnEnum.getByValue(deptDn) != null) {
            return deptDn;
        }
        String[] orgDnArr = deptDn.split(Constants.STRING_SPLIT);
        if (orgDnArr.length > 1) {
            String cmpDn = orgDnArr[orgDnArr.length - 2]
                + Constants.STRING_SPLIT + orgDnArr[orgDnArr.length - 1];
            if (CmpDnEnum.getByValue(cmpDn) != null) {
                return cmpDn;
            }
            if (CmpDnEnum.getByValue(orgDnArr[orgDnArr.length - 1]) != null) {
                return orgDnArr[orgDnArr.length - 1];
            }
        }
        return "";
    }

    /**
     * 将组织dn转换成hr组织名称.
     * @param orgDn 组织dn
     * @return 组织名称
     */
    public static String convertDnToFullName(final String orgDn) {
        if (StringUtils.isBlank(orgDn)) {
            return null;
        }

        if (StringUtils.equals(CmpDnEnum.ZMCC.getValue(), orgDn)) {
            return CmpDnEnum.ZMCC.getName();
        }

        String[] orgDnArr = orgDn.split(Constants.STRING_SPLIT);
        List<String> results = Lists.newArrayList();
        for (int index = orgDnArr.length - 2; index >= 0; index--) {
            String orgNameTmp = orgDnArr[index];
            if (index != orgDnArr.length - 2) {
                results.add(orgNameTmp.replace("OU=", ""));
                continue;
            }
            if (SUB_COMPANY_DN_PATTERN.matcher(orgNameTmp).find()) {
                results.add(CmpDnEnum.getNameByValue(orgNameTmp + Constants.STRING_SPLIT + CmpDnEnum.ZMCC.getValue()));
                continue;
            } else {
                results.add(CmpDnEnum.ZMCC.getName());
                results.add(orgNameTmp.replace("OU=", ""));
            }
        }
        return StringUtils.join(results.iterator(), Constants.STRING_JOIN_XG);
    }
}
